package com.example.document.local

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.get
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.document.R
import com.example.document.databinding.ActivityLocalBinding
import com.example.lib_adapter.BaseQuickAdapter
import com.example.lib_base.BaseActivity
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlin.math.log

@Route(path = "/doc/LocalActivity")
class LocalActivity : BaseActivity<ActivityLocalBinding,LocalViewModel>() {
    val localAdapter by lazy { LocalAdapter() }
    override fun createVM(): LocalViewModel {
        return ViewModelProvider(this).get(LocalViewModel::class.java)
    }

    override fun createV(): ActivityLocalBinding {
        return ActivityLocalBinding.inflate(layoutInflater)
    }

    override fun bindState() {
        lifecycleScope.launch {
            vm.mutableContainer.uiFlow.collect{
                val state = it as LocalState
                if(state.localState){
                    Log.i("===本地文件",state.datas.toString())
                    localAdapter.addAll(state.datas)
                }
            }
        }
    }

    override fun initData() {
        vm.scanFiles()
    }

    override fun initView() {
        vb.localBack.setOnClickListener{
            finish()
        }

        vb.localUpload.setOnClickListener {
            val bundle = Bundle()
            localAdapter.data.forEach {
                if(it.sel){
                    bundle.putString("name",it.name)
                    bundle.putString("path",it.path)
                }
            }
            val intent = Intent()
            intent.putExtras(bundle)
            setResult(RESULT_OK,intent)
            finish()
        }

        vb.localRv.apply {
            layoutManager=LinearLayoutManager(this@LocalActivity)
            adapter=localAdapter
        }

        localAdapter.setOnItemChildClickListaner(object :BaseQuickAdapter.OnItemChildClickListener{
            override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, id: Int, position: Int) {
                //获取当前的选中状态
                val sel = localAdapter.data[position].sel
                localAdapter.data.forEach {
                    it.sel=false
                }
                //设置状态为反选
                localAdapter.data[position].sel=!sel
                localAdapter.notifyDataSetChanged()
            }

        })

    }
}